﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Bymed.RegistrationCodeManager.Service.Shared;
using Miris.HumanMilkAnalyser.DataModel;
using Miris.HumanMilkAnalyser.Service.Shared;

namespace Miris.HumanMilkAnalyser.Service
{
    public class RegistrationCodeConfigurationService
    {
        /// <summary>
        /// Load RegistrationCodeConfiguration instance from App.Config
        /// </summary>
        /// <returns></returns>
        public RegistrationCodeConfiguration Load()
        {
            return new RegistrationCodeConfiguration
            {
                ComputerNumber = RegistrationCodeManagerUtility.GetFirstEthernetMacAddress(),
                RegistrationCode = (string)ConfigFileUtility.GetValue(ConfigurationConstant.RegistrationCode),
                AvailableAuthorisedUsageCount = GeneralUtility.GetAvailableAuthorisedUsageCount().ToString()
            };
        }

        /// <summary>
        /// Save provided RegistrationCodeConfiguration instance to App.Config
        /// </summary>
        /// <param name="entity"></param>
        public void Save(RegistrationCodeConfiguration entity)
        {
            entity.RegistrationCode = entity.RegistrationCode.Trim();

            // If the Registration Code changed then need to refresh the AvailableAuthorisedUsageCount.
            if ((string)ConfigFileUtility.GetValue(ConfigurationConstant.RegistrationCode) != entity.RegistrationCode)
            {
                ConfigFileUtility.ChangeValue(ConfigurationConstant.AvailableAuthorisedUsageCount, entity.AvailableAuthorisedUsageCount);
            }

            ConfigFileUtility.ChangeValue(ConfigurationConstant.RegistrationCode, entity.RegistrationCode);
        }

        /// <summary>
        /// Decrease the AvailableAuthorisedUsageCount if it is greater than 0. Because -1 means NO limit for usage.
        /// </summary>
        public void DecreaseAvailableAuthorisedUsageCount()
        {
            var availableAuthorisedUsageCount = GeneralUtility.GetAvailableAuthorisedUsageCount();

            if (availableAuthorisedUsageCount == 0)
            {
                throw new System.Exception("当前设备已超出授权次数，请与系统提供商联系以获取技术支持。");
            }

            if (availableAuthorisedUsageCount > 0)
            {
                availableAuthorisedUsageCount -= 1;
                var encryptedAvailableAuthorisedUsageCount = RegistrationCodeManagerUtility.EncryptString(availableAuthorisedUsageCount.ToString());

                ConfigFileUtility.ChangeValue(ConfigurationConstant.AvailableAuthorisedUsageCount, encryptedAvailableAuthorisedUsageCount);
                ConfigFileUtility.RefreshAppSettingsSection();
            }
        }
    }
}
